package com.experiment.springbootconfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
//import org.hibernate.validator.internal.util.logging.LoggerFactory;
//import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
//import lombok.extern.slf4j.Slf4j;
//import java.util.logging.Logger;


@EnableConfigurationProperties(InitConfigurationProperties.class)
public class AutoConfig {
    @Bean
    @ConditionalOnProperty(prefix = "bin.auto",name = "enable",havingValue = "false")
    CommandLineRunner setCommandLineRunner(Environment environment){
        return new InitCommandLineRunner(environment);
    }

    //@Bean("applicationEventMulticaster")
    @Bean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    ApplicationEventMulticaster InitApplicationEventMulticaster(ThreadPoolTaskExecutor taskExecutor){
        SimpleApplicationEventMulticaster eventMulticaster=new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(taskExecutor);
        return eventMulticaster;
    }

    static class NoticeEvent extends ApplicationEvent{

        private static final Logger logger= LoggerFactory.getLogger(NoticeEvent.class);
        //private static final Logger l
        private final String message;

        public NoticeEvent(String message){
            super(message);
            this.message=message;
            logger.info("success!message:"+message);
            //logger.info("success!message:{}",message);
        }

        public String getMessage(){
            return message;
        }
    }


    @Component
    static class NoticeListener implements ApplicationListener<NoticeEvent>{

        private static final Logger logger= LoggerFactory.getLogger(NoticeListener.class);

        @Override
        public void onApplicationEvent(NoticeEvent noticeEvent){
            logger.info("NoticeEvent success!Thread sleeping time is two second...");
            try {
                Thread.sleep(2000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            logger.info("NoticeEvent message is:"+noticeEvent.getMessage());
        }

    }
}
